import sys
import asyncio
from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget
from PyQt5.QtCore import QObject, pyqtSignal,QThread

class Worker(QObject):
    finished = pyqtSignal()

    async def async_task(self):
        print("Task started")
        await asyncio.sleep(5)  # 模拟耗时5秒
        print("Task finished")
        self.finished.emit()

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.button = QPushButton("Start Non-Blocking Task", self)
        self.button.clicked.connect(self.start_worker)
        layout = QVBoxLayout(self)
        layout.addWidget(self.button)

    def start_worker(self):
        worker = Worker()
        thread = QThread()
        worker.moveToThread(thread)
        
        # 连接信号和槽
        thread.started.connect(worker.async_task)
        worker.finished.connect(thread.quit)
        worker.finished.connect(self.on_task_finished)
        
        thread.start()

    def on_task_finished(self):
        print("Task completed without blocking UI")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())